<?php

namespace MoChat\App\Statistic\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use MoChat\App\Client\Model\Client;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use TheSeer\Tokenizer\Exception;
use Hyperf\Command\Annotation\Command;

/**
 * @Command
 */
class ClientBindingCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('clientBinding');
    }

    public function configure()
    {
        parent::configure();
        $this->addOption('clear', 'C', InputArgument::OPTIONAL, '清除redis', 0);
        $this->setDescription('客户绑定任务');
    }

    public function handle()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);
        $clear = $this->input->getOption('clear');
        if ($clear) {
            $redis->del('ClientBindingCommand_key');
        }
        $bool = $redis->get('ClientBindingCommand_key');
        if ($bool) {
            $this->line('上一个客户绑定任务脚本程序正在执行中', 'error');
        } else {
            $redis->set('ClientBindingCommand_key', true,300);
            Db::beginTransaction();
            try {
                $client = Db::table('client')
                    ->join('work_employee as employee', 'employee.name', '=', 'client.b2b_manager_name')
                    ->select([
                        'employee.id as work_employee_id',
                        'client.id as client_id',
                    ])
                    ->where('client.work_employee_id',0)
                    ->orderBy('client.id', 'asc')->limit(2000)->get();
                $client || $client = collect([]);
                $client = $client->toArray();
                if (empty($client)) {
                    $redis->set('ClientBindingCommand_key_max_id', 0);
                    throw new Exception('数据不存在');
                }
                foreach ($client as $item) {
                    if (!empty($item->work_employee_id)) {
                        Client::where('id', $item->client_id)->update([
                            'work_employee_id' => $item->work_employee_id,
                            'updated_at' => date('Y-m-d H:i:s'),
                        ]);
                    }
                }
                Db::commit();
            } catch (\Throwable $throwable) {
                dump($throwable->getMessage());
                Db::rollBack();
            }
            $redis->del('ClientBindingCommand_key');
            $this->line('客户绑定任务脚本处理完成', 'info');
        }
    }
}
